<?php


namespace app\index\model;


use think\Model;

class Login extends Model
{
    protected $pk = 'id';
    protected $name = 'user';

    public function doLogin($username,$password): array
    {
        $user_data=$this->alias('u')->field('u.id,u.user_name,u.password,u.login_count,u.role,u.role_detail_id,u.group_id,r.role_name,rd.role_name role_detail_name,g.group_name')
            ->join('__ROLE__ r','u.role=r.id','left')
            ->join('role_detail rd','u.role_detail_id=rd.id','left')
            ->join('__GROUP__ g','u.group_id=g.id','left')
            ->where('user_name',$username)
            ->where('status',1)
            ->find();
        if(empty($user_data)){
            return ['status'=>false,'msg'=>'用户不存在或已被禁用'];
        }
        if($user_data['login_count']>=5){
            $this->updateUserStatus(['id'=>$user_data['id'],'status'=>0]);
            return ['status'=>false,'msg'=>'用户已被禁用'];
        }
        if($user_data['password']!==$password){
            $this->updateUserStatus(['id'=>$user_data['id'],'login_count'=>$user_data['login_count']+1]);
            return ['status'=>false,'msg'=>'用户不存在或密码错误'];
        }
        if($user_data['role_detail_name']){
            $user_data['role_name'] .= $user_data['role_detail_name'];
        }
        //获取可访问菜单
        $menus=MenuRole::getUserMenu($user_data);
        /*$menus=[];
        foreach ($menu as $key=>$value){
            $menus[]=$value['url_path'];
        }*/
        $action_role=ActionRole::getViewActionRole($user_data);
        //登录成功更新
        $this->updateUserStatus(['id'=>$user_data['id'],'login_count'=>0,'login_time'=>date('Y-m-d H:i:s')]);
        return ['status'=>true,'data'=>$user_data,'menu'=>$menus,'action'=>$action_role];
    }

    public function updateUserStatus($data){
        $this->allowField(true)->save($data,['id'=>$data['id']]);
    }
}